package yongxin.controller.processreport;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.chromate.ChromateEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.chromate.ChromateServiceI;
import yongxin.service.matchinegroup.MatchinegroupServiceI;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.tasks.TasksServiceI;
import yongxin.service.workshop.WorkshopServiceI;

/**   
 * @Title: Controller
 * @Description: 工序汇报
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/processReport111Controller")
public class CopyOfProcessReportP11Controller extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CopyOfProcessReportP11Controller.class);

	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ChromateServiceI chromateService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private WorkshopServiceI workshopService;
	
	@Autowired
	private TasksServiceI tasksService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "processReport")
	public ModelAndView processReport(HttpServletRequest request) {
		String process=request.getParameter("process");
		request.setAttribute("process", process);
		
		return new ModelAndView("yongxin/process/processReportList_p11");
		
		
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		String process=request.getParameter("process");
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		//查询条件组装器
		cq.eq("cprocess", process);
		if(StringUtil.isEmpty(processReport.getFstate())){
		cq.in("fstate", new Object[]{"0","1"});
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
		//String total_trzl = String.valueOf(processService.findOneForJdbc("select sum(CONVERT(numeric(19,2),ftrzl)) sum_trzl from t_processreport where cprocess = 'p11' and fstate in('0','1')").get("sum_trzl"));
		//total_trzl = total_trzl == "null"?"":total_trzl;
		//dataGrid.setFooter("fbcph:投入总计 ,fworkshop:" + total_trzl + ",ftrkd:合计,ftrzl,fcczl,fbfzl");
		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		
		TagUtil.datagrid(response, dataGrid);
		
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}

		
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();
        
		// 分卷信息
		String ftrhds = request.getParameter("ftrhds");
		String ftrkds = request.getParameter("ftrkds");
		String ftrzls = request.getParameter("ftrzls");

		String[] ffjhs = request.getParameterValues("ffjhs");
		String[] fcds = request.getParameterValues("fcds");
		String[] ffqzls = request.getParameterValues("ffqzls");
		String[] fnotes = request.getParameterValues("fnotes");
		String[] fnprocess = request.getParameterValues("fnprocess");

		if (ffjhs != null && ffjhs.length > 0) // 分卷
		{
			if (StringUtil.isNotEmpty(processReport.getFstate())) // 汇报操作
			{
			

				// 分卷汇报
				if (!ftrzls.equals("0") && !ftrzls.equals("0.00"))
				{
					for (int i = 0; i < ffjhs.length; i++)
					{

						try
						{
							// ProcessReportEntity t = new
							// ProcessReportEntity();
							// MyBeanUtils.copyBeanNotNull2Bean(processReport,
							// t);

							if (fnprocess[i] != null && fnprocess[i].equals("over")) // 入库
							{

								ChromateEntity product = new ChromateEntity();
								product.setFbcph(processReport.getFbcph());
								product.setFtrkd(ftrkds);
								product.setFtrhd(ftrhds);
								product.setFtrzl(ftrzls);
								product.setFfjh(ffjhs[i]);
								product.setFcd(fcds[i]);
								product.setFfqzl(ffqzls[i]);
								product.setNprocess(fnprocess[i]);
								product.setFnote(fnotes[i]);
								product.setFreportId(processReport.getId());
								systemService.save(product);
                                
								/*
								ProcessEntity entity = new ProcessEntity();
								entity.setFbcph(ffjhs[i]);
								entity.setFprocess(fnprocess[i]);
								processService.save(entity);
                                */
								systemService.save(product);

							} else   	// 不入库
							{
								//  保存本道工序记录
								ProcessReportEntity cprocessReport = new ProcessReportEntity();
								cprocessReport.setCprocess(processReport.getCprocess());
								cprocessReport.setFbcph(ffjhs[i]);
								cprocessReport.setFtrhd(ftrhds);
								cprocessReport.setFtrkd(ftrkds);
								cprocessReport.setFtrzl(ffqzls[i]);
								cprocessReport.setNprocess(fnprocess[i]);
								cprocessReport.setFisleft("1");       //  标记为 镀铬 分卷    未入库的  
								cprocessReport.setFstate("2");
								processReportService.save(cprocessReport);
								
								if(!fnprocess[i].equals(processReport.getCprocess()))
								{
								ProcessEntity entity2 = new ProcessEntity();
								entity2.setFreportid(cprocessReport.getId());
								entity2.setFbcph(ffjhs[i]);
								entity2.setFprocess(processReport.getCprocess());
								processService.save(entity2);
								}
								// 保存下一道工序记录
								ProcessReportEntity nprocessReport = new ProcessReportEntity();
								nprocessReport.setCprocess(fnprocess[i]);
								nprocessReport.setFbcph(ffjhs[i]);
								nprocessReport.setFtrhd(ftrhds);
								nprocessReport.setFtrkd(ftrkds);
								nprocessReport.setFtrzl(ffqzls[i]);
								nprocessReport.setFisleft("1");     //  标记为镀铬分卷  未入库的       作用是方便查看工序流转图时不显示母卷信息
								nprocessReport.setFstate("0");
								processReportService.save(nprocessReport);

								ChromateEntity product = new ChromateEntity();
								product.setFbcph(processReport.getFbcph());
								product.setFtrkd(ftrkds);
								product.setFtrhd(ftrhds);
								product.setFtrzl(ftrzls);
								product.setFfjh(ffjhs[i]);
								product.setFcd(fcds[i]);
								product.setFfqzl(ffqzls[i]);
								product.setNprocess(fnprocess[i]);
								product.setFnote(fnotes[i]);
								product.setFreportId(nprocessReport.getId());
								systemService.save(product);

								ProcessEntity entity = new ProcessEntity();
								entity.setFreportid(nprocessReport.getId());
								entity.setFbcph(ffjhs[i]);
								entity.setFprocess(fnprocess[i]);
								processService.save(entity);
							}

						} catch (Exception e)
						{
							e.printStackTrace();
							message = "工序汇报失败";
						}
					}
				}
				
				try
				{

					message = "工序汇报成功";

					// 剩余重量为0 下一道工序为结束
					if (processReport.getNprocess().equals("over"))
					{
						ProcessEntity entity = new ProcessEntity();
						entity.setFbcph(processReport.getFbcph());
						entity.setFprocess(processReport.getNprocess());
						processService.save(entity);
						
						ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
						MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
						t.setFstate("2");
						t.setNprocess("over");
						processReportService.saveOrUpdate(t);

						
						// 计算任务单成材率
						String bcph = processReport.getFbcph();
						if (bcph.split("-").length > 0)
						{
							bcph = bcph.split("-")[0];
						}
						
					} else   // 剩余重量 不为空和0时保存为本道工序记录
					
					{   
						ProcessEntity entity = new ProcessEntity();
						entity.setFbcph(processReport.getFbcph());
						entity.setFprocess(processReport.getNprocess());
						processService.save(entity);
						
						ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
						MyBeanUtils.copyBeanNotNull2Bean(processReport, t);
						t.setFstate("2");
						processReportService.saveOrUpdate(t);

						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setCprocess(processReport.getNprocess());
						nprocessReport.setFbcph(processReport.getFbcph());
						nprocessReport.setFtrhd(processReport.getFtrhd());
						nprocessReport.setFtrkd(processReport.getFtrkd());
						nprocessReport.setFtrzl(processReport.getFcczl());
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);

					
						entity.setFreportid(nprocessReport.getId());
						processService.saveOrUpdate(entity);
					}

				} catch (Exception e)
				{
					e.printStackTrace();
					message = "工序汇报失败";
				}
				
			}
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ProcessReportEntity processReport, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(processReport.getId())) {
			processReport = processReportService.getEntity(ProcessReportEntity.class, processReport.getId());

			if (processReport.getFstate().equals("2"))       // 查看  已完工  信息
			{

				String hql = " from ChromateEntity where 1 = 1 and fbcph = ? and freportId = ?";
				List<ChromateEntity> list = chromateService.findHql(hql, processReport.getFbcph(), processReport.getId());
				List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
				req.setAttribute("workshopList", workshopList);

				req.setAttribute("processReportPage", processReport);
				req.setAttribute("productList", list);
				return new ModelAndView("yongxin/process/processReport_p11_2");
			} else
			{

				String hql = " from ChromateEntity where 1 = 1 and fbcph = ? ";
				List<ChromateEntity> list = chromateService.findHql(hql, processReport.getFbcph());
				List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
				req.setAttribute("workshopList", workshopList);
				req.setAttribute("processReportPage", processReport);
				req.setAttribute("productList", list);
				return new ModelAndView("yongxin/process/processReport_p11");

			}
		}
		return new ModelAndView("yongxin/process/processReport_p11");
	}
	
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		String id=request.getParameter("id");
		if (StringUtil.isEmpty(id)) {
			id="nprocess";
		}
		String ofbcph="";
		if(fbcph.indexOf("-")>0){
			ofbcph=fbcph.substring(0,fbcph.indexOf("-"));
		}
		Object[] object=new Object[3];
		object[0]=ofbcph;
		object[1]=fbcph;
		object[2]=fbcph;
		
		String sql=" select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " +
				"   from t_process tp  " +
				"   left join (select tst.typecode,tst.typename " +
				"    from t_s_type tst,t_s_typegroup tstg  " +
				"    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " +
				"     on tp.fprocess=dic.typecode      " +
				"      where tp.fbcph=? and create_date< ( " +
				"		select min(create_date) from t_process t1 where t1.fbcph=? " +
				"      ) " +
				" union " +
				"   select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " +
				"   from t_process tp  " +
				"   left join (select tst.typecode,tst.typename " +
				"    from t_s_type tst,t_s_typegroup tstg  " +
				"    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " +
				"     on tp.fprocess=dic.typecode     " +
				"  where tp.fbcph=?    order by tp.create_date ";
		
		String sql2="select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 +=" where tst.typegroupid=tstg.ID ";
		sql2 +=" and tstg.typegroupcode='ccgx' and tst.typecode!='p1'";
		
		List<Map<String,Object>> maplist=null;
		List<Map<String,Object>> maplist2=null;
		 try{
			 maplist=systemService.findForJdbc(sql, object);
			 maplist2=systemService.findForJdbc(sql2,null);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(maplist);
		 j.setMsg(createSelecte(maplist2,id));
		 
		return j;
	}
	
	private String createSelecte(List<Map<String,Object>> maplist,String id){
		String select="<select id='nprocess' name='"+id+"' class='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist) {
			select +="<option value="+map.get("typecode")+">"+map.get("typename")+"</option>";
		}
		//select = select.replaceAll(select.substring(67,98), "");
		return select;
	}
	
	
	
}
